part of login;

class ForgotPanel extends StatefulWidget {
  const ForgotPanel({Key? key}) : super(key: key);

  @override
  State<ForgotPanel> createState() => _ForgotPanelState();
}

class _ForgotPanelState extends State<ForgotPanel>
    with SingleTickerProviderStateMixin {
  final FocusNode _usernameFocusNode = FocusNode();
  final FocusNode _passwordFocusNode = FocusNode();
  final FocusNode _verifyFocusNode = FocusNode();

  String username = '';
  String verifycode = '';
  String password = '';

  bool btnEnabled = true;
  bool _isSubmitting = false;
  int counterSeconds = 0;
  late Timer counter;

  void _onCounter(Timer timer) {
    if (timer.tick >= 60) {
      counter.cancel();
    }
    if (!mounted) return;
    setState(() {
      counterSeconds = math.max(0, 60 - timer.tick);
      if (counterSeconds <= 0) btnEnabled = true;
    });
  }

  _sendVerify() async {
    if (!btnEnabled) return;
    if (username.isEmpty) {
      toast('请填写手机号码');
      _usernameFocusNode.requestFocus();
      return;
    }
    String captcha = '';

    await MyDialog.alert(
      CaptchaDialog(
        onChanged: (newValue) {
          captcha = newValue;
        },
      ),
      buttonText: '确定',
    );
    if (captcha.isEmpty) return;

    btnEnabled = false;
    counter = Timer.periodic(const Duration(seconds: 1), _onCounter);

    final result = await app.login.sendSMS(username, captcha, 'verify');
    if (result.code == 1) {
      toast('验证码发送成功');
    } else {
      //counter.cancel();
      toast(result.message);
    }
  }

  _doForgot() async {
    if (username.isEmpty) {
      toast('请填写用户名');
      return;
    }
    if (verifycode.isEmpty) {
      toast('请填写验证码');
      return;
    }
    if (password.isEmpty) {
      toast('请填写密码');
      return;
    }
    logger.info([username, password]);
    _usernameFocusNode.unfocus();
    _passwordFocusNode.unfocus();
    _verifyFocusNode.unfocus();
    setState(() {
      _isSubmitting = true;
    });
    final indexState = _IndexPageState.of(context);
    final result = await app.login.doForgot({
      'account': username,
      'password': password,
      'verify': verifycode,
      'type': 'mobile',
    });
    if (result.code == 1) {
      toast(result.message);
      indexState.changePanel('login', direction: 'lr');
    } else {
      toast(result.message);
    }
    setState(() {
      _isSubmitting = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        const SizedBox(height: 10),
        TextField(
          maxLength: 30,
          focusNode: _usernameFocusNode,
          cursorColor: Colors.white,
          style: const TextStyle(color: Colors.white, height: 1.5),
          strutStyle: const StrutStyle(height: 1.5, fontSize: 16.0),
          textAlignVertical: TextAlignVertical.center,
          decoration: LoginTheme.inputDecoration('手机号码', icon: Icons.person),
          onChanged: (String value) {
            username = value;
          },
        ),
        const SizedBox(height: 20),
        TextField(
          maxLength: 6,
          focusNode: _verifyFocusNode,
          style: const TextStyle(color: Colors.white, height: 1.5),
          strutStyle: const StrutStyle(height: 1.5, fontSize: 16.0),
          textAlignVertical: TextAlignVertical.center,
          keyboardType: const TextInputType.numberWithOptions(),
          onChanged: (String value) {
            verifycode = value;
          },
          decoration: LoginTheme.inputDecoration(
            '验证码',
            icon: Icons.check_circle,
            action: Padding(
              padding: const EdgeInsets.symmetric(vertical: 3, horizontal: 0),
              child: ElevatedButton(
                onPressed: () {
                  _sendVerify();
                },
                style: ButtonStyle(
                  backgroundColor: MaterialStateProperty.all(Colors.white54),
                ),
                child: Text(
                  '发送${btnEnabled ? '' : "($counterSeconds)"}',
                  style: const TextStyle(color: Colors.black54),
                ),
              ),
            ),
          ),
        ),
        const SizedBox(height: 20),
        TextField(
          maxLength: 30,
          focusNode: _passwordFocusNode,
          style: const TextStyle(color: Colors.white, height: 1.5),
          strutStyle: const StrutStyle(height: 1.5, fontSize: 16.0),
          textAlignVertical: TextAlignVertical.center,
          obscureText: true,
          onChanged: (String value) {
            password = value;
          },
          decoration: LoginTheme.inputDecoration('新密码', icon: Icons.lock),
        ),
        const SizedBox(height: 20),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: StateButton(
            onPressed: _doForgot,
            text: '重置密码',
            isLoading: _isSubmitting,
          ),
        ),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 10),
          child: Row(
            children: <Widget>[
              TextButton(
                onPressed: () {
                  _IndexPageState.of(context)
                      .changePanel('login', direction: 'lr');
                },
                child: Text('返回登录', style: LoginTheme.linkStyle),
              ),
              const Spacer(),
            ],
          ),
        )
      ],
    );
  }
}
